﻿using FarseerPhysics;
using FarseerPhysics.Dynamics;
using FarseerPhysics.Factories;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Syngine;
using Syngine.Physics;
using Syngine.Physics.Components;

namespace BenchMark.ShootingGame
{
	public class TestText : DrawableSprite
	{
		private SpriteFont _font;
		private Vector2 _textDimensions;
		private readonly Vector2 _forceConstant = new Vector2(500.0f, 500.0f);

		protected override void UpdateCore(UpdateContext context)
		{
			var state = Mouse.GetState();

			if (state.LeftButton == ButtonState.Pressed)
			{
				// Convert the touch position (screen coords) to world coords.
				Vector2 worldTouchPosition = ConvertUnits.ToSimUnits(new Vector2(state.X, state.Y));

				// Get the direction the force should be applied.
				Vector2 direction = Vector2.Normalize(Body.Position - worldTouchPosition);

				// Get the distance between the body and touch positions.
				float distance = Vector2.Distance(Body.Position, worldTouchPosition);

				// Get the force.  Deminishes the larger the distance.
				Vector2 force = ((_forceConstant * direction) / distance);

				// Apply the force to the body.
				Body.ApplyForce(force);
			}
		}

		public override void LoadContent(LoadContext context)
		{
			_font = context.Content.Load<SpriteFont>("spriteFont1");
			_textDimensions = _font.MeasureString("Ohhhhh, Yeeeahh!");

			var game = GameContext.Game;
			var width = game.GraphicsDevice.Viewport.Width / 2;
			var height = game.GraphicsDevice.Viewport.Height / 2;
			var position = new Vector2(width - (_textDimensions.X / 2), height - (_textDimensions.Y / 2));
			Body = BodyFactory.CreateRectangle(WorldContext.World, ConvertUnits.ToSimUnits(_textDimensions.X), ConvertUnits.ToSimUnits(_textDimensions.Y), 1f);
			Body.BodyType = BodyType.Dynamic;
			Body.Position = new Vector2(ConvertUnits.ToSimUnits(position.X), ConvertUnits.ToSimUnits(position.Y));
			Body.Restitution = 0.8f;
			Body.Mass = 1.0f;
		}

		public override void UnloadContent()
		{
		}

		protected override void DrawCore(DrawContext context)
		{
			var x = ConvertUnits.ToDisplayUnits(Body.Position.X);
			var y = ConvertUnits.ToDisplayUnits(Body.Position.Y);
			context.SpriteBatch.DrawString(_font, "Ohhhhh, Yeeeahh!", new Vector2(x, y), Color.White, Body.Rotation, _textDimensions / 2, 1.0f, SpriteEffects.None, 1.0f);
		}
	}
}